<?php

namespace app\admin\controller\auth;

use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\admin\model\AdminMoneyLog;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Db;
use think\Validate;

/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Admin extends Backend
{

    /**
     * @var \app\admin\model\Admin
     */
    protected $model = null;
    protected $selectpageFields = 'id,username,nickname,avatar';
    protected $searchFields = 'id,username,nickname';
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        //代理只能看到自己创建的商户
        if ($child = $this->model->getAgentChild($this->auth->id)) {
            $this->childrenAdminIds = $child;
        }

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }



                //代理可以创建代理

                if ($n['group_id']==3) {
                    $temp[$n['group_id']] = $n['name'];
                }


                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }

        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $childrenGroupIds = $this->childrenGroupIds;
            $groupName = AuthGroup::where('id', 'in', $childrenGroupIds)
                ->column('id,name');
            $authGroupList = AuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
                ->field('uid,group_id')
                ->select();

            $adminGroupName = [];
            foreach ($authGroupList as $k => $v) {
                if (isset($groupName[$v['group_id']])) {
                    $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
                }
            }
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $adminGroupName[$this->auth->id][$n['id']] = $n['name'];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['manystoreshop'])
                ->where($where)
                ->where($this->model->getTable() . '.id', 'in', $this->childrenAdminIds)
                //->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $k => &$v) {
                $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
                $v['groups'] = implode(',', array_keys($groups));
                $v['groups_text'] = implode(',', array_values($groups));

                $v->visible(['state', 'id', 'username', 'nickname', 'groups_text', 'email', 'status', 'logintime', 'money', 'agent_domain', 'agent_system_name']);
                $v->visible(['manystoreshop']);
            }
            unset($v);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {

        if ($this->request->isPost()) {
            $this->token();
            $this->check();
            $params = $this->request->post("row/a");
            $group = $this->request->post("group/a");

            $sellerconfigdata = model('SellerConfig')->get(['id' => $params['config_id']]);
            $params['last_aivideo_nums']=$sellerconfigdata->video_times;
            $params['money']=$sellerconfigdata->money;


            $AuthGroupAccessData=AuthGroupAccess::where('uid', $this->auth->id)->find();


            if ($AuthGroupAccessData->group_id==3) {//代理添加商户
                $data=$this->model->get(['id' => $this->auth->id]);
                if ($data->last_aivideo_nums<$params['last_aivideo_nums']) {
                     $this->error('代理视频额度不足，无法创建账号');
                }
                // if ($data->money<$params['money']) {
                //      $this->error('代理余额不足，无法为商户添加套餐');
                // }


                if ($group[0]==3) {
                    if ($data->agent_power==0) {
                       $this->error('您无法创建代理');
                    }
                }

            }


            //admin创建代理
            if ($this->auth->id==1) {
                if ($group[0]==3) {

                    if (config('site.severmit')==1) {
                        if ($params['douyin_type']==2) {
                            $this->error('平台为公用应用，代理不得为平台应用');
                        }
                    }else{
                        if ($params['douyin_type']==1) {
                            $this->error('平台为平台应用，代理不得为平台公用应用');
                        }
                    }




                    if ($params['douyin_type']==3) {
                       if ($params['client_key']==''||$params['client_secret']=='') {
                            $this->error('请填写抖音Client Key以及抖音Client Secret');
                       }


                       if ($params['agent_domain']=='') {
                            $this->error('请填写代理商域名');
                       }

                    }



                    if ($params['douyin_type']==2) {
                       if ($params['system_domain']=='') {
                            $this->error('请填写系统域名');
                       }
                    }



                    $params['admin_subordinate']=1;

                }
            }






            if ($params) {
                if (!Validate::is($params['password'], '\S{6,16}')) {
                    $this->error(__("Please input correct password"));
                }
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $params['pid'] = $this->auth->id;
                $result = $this->model->validate('Admin.add')->save($params);
                session('admin.agent_system_name', NULL);
                if ($result === false) {
                    $this->error($this->model->getError());
                }



                //扣除代理自身的余额
                if ($AuthGroupAccessData->group_id==3) {
                    $this->model->where('id', $this->auth->id)->setDec('money', $params['money']);
                    $this->model->where('id', $this->auth->id)->setDec('last_aivideo_nums', $params['last_aivideo_nums']);
                    AdminMoneyLog::create([
                        'admin_id'     => $this->auth->id,
                        'type'   => 2,
                        'money'       => $params['money'],
                        'note'  => '代理添加下级扣除余额',
                        'create_at'  => date('Y-m-d h:i:s', time()),
                    ]);

                }




                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!in_array($row->id, $this->childrenAdminIds)) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $this->check();
            $params = $this->request->post("row/a");
            $group = $this->request->post("group/a");


            if ($this->auth->id!=1) {
                if ($ids==$this->auth->id) {
                    $this->error('无法修改自己账户');
                }
            }





            //admin创建代理
            if ($this->auth->id==1) {
                if ($group[0]==3) {

                    if (config('site.severmit')==1) {
                        if ($params['douyin_type']==2) {
                            $this->error('平台为公用应用，代理不得为平台应用');
                        }
                    }else{
                        if ($params['douyin_type']==1) {
                            $this->error('平台为平台应用，代理不得为平台公用应用');
                        }
                    }




                    if ($params['douyin_type']==3) {
                       if ($params['client_key']==''||$params['client_secret']=='') {
                            $this->error('请填写抖音Client Key以及抖音Client Secret');
                       }


                       if ($params['agent_domain']=='') {
                            $this->error('请填写代理商域名');
                       }

                    }



                    if ($params['douyin_type']==2) {
                       if ($params['system_domain']=='') {
                            $this->error('请填写系统域名');
                       }
                    }



                    $params['admin_subordinate']=1;

                }
            }







            if ($params) {


                if ($ids==$this->auth->id) {
                    if ($row->agent_power!=$params['agent_power']) {
                         $this->error("您无法修改代理权限");
                    }
                }

                if ($params['password']) {
                    if (!Validate::is($params['password'], '\S{6,16}')) {
                        $this->error(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                    'username' => 'require|regex:\w{3,12}|unique:admin,username,' . $row->id,
                    'email' => 'require|email|unique:admin,email,' . $row->id,
                    'password' => 'regex:\S{32}',
                ]);
                $result = $row->validate('Admin.edit')->save($params);
                session('admin.agent_system_name', NULL);
                if ($result === false) {
                    $this->error($row->getError());
                }

                // 先移除所有权限
                model('AuthGroupAccess')->where('uid', $row->id)->delete();

                $group = $this->request->post("group/a");

                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);

                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $row->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $ids = array_intersect($this->childrenAdminIds, array_filter(explode(',', $ids)));
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenGroupIds;
            $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
                $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
            })->select();
            if ($adminList) {
                $deleteIds = [];
                foreach ($adminList as $k => $v) {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_values(array_diff($deleteIds, [$this->auth->id]));
                if ($deleteIds) {
                    $this->model->destroy($deleteIds);
                    model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
                    $this->success();
                }
            }
        }
        $this->error(__('You have no permission'));
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * 下拉搜索
     */
    public function selectpage()
    {
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'id';
        return parent::selectpage();
    }


    /**
     * 用户套餐
     * @param
     */
    public function sellerconfig($ids)
    {

        $admin_config = \app\admin\model\Admin:: get($ids, 'sellerconfig');

        if (!$admin_config->agent_level) $this->error("该商户未绑定所属组别");


        if (!$admin_config->sellerconfig->id) $this->error("该商户未绑定套餐");


        $this->view->assign("sellerconfig", $admin_config->sellerconfig);
        $shop_days = (int)((time() - $admin_config->createtime) / 86400);


        //天数额度
        /*    if ($config->days) {
                if ($admin_config->createtime + ($config->days * 86400) < time()) $this->error("天数已经超过套餐额度,请联系您的代理商");

            }*/

        $child = model('Admin')->getAgentChild($ids);
        if ($child) {
            $video_times = model('Admin')->where('id', 'in', $child)->sum('aivideo_nums');
            $activity_nums = model('Admin')->where('id', 'in', $child)->sum('activity_nums');
        } else {
            $video_times = model('Admin')->where('id', $ids)->sum('aivideo_nums');
            $activity_nums = model('Admin')->where('id', $ids)->sum('activity_nums');
        }

        $dbPrefix = config('database.prefix');
        $userInfo = Db::table($dbPrefix . 'admin')->find(intval($ids));

        //视频额度
        /*     if ($config->video_times && $video_times > $config->video_times) {
                 $this->error("创建视频数已经超过套餐额度,请联系您的代理商");

             }
             //活动数量额度
             if ($config->video_activitys && $activity_nums > $config->video_activitys) {
                 $this->error("创建活动数量已经超过套餐额度,请联系您的代理商");

             }*/
        $this->view->assign("shop_days", $shop_days);
        $this->view->assign("video_times", $video_times);
        $this->view->assign("activity_nums", $activity_nums);
        $this->view->assign("shop_nums", ($child) ? (count($child)) : (0));
        $this->view->assign("userInfo", $userInfo);
        return $this->view->fetch();
    }



    /**
     * 充值金额
     * @param
     */
    public function addmoney($ids=null){

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");


            $AuthGroupAccessData=AuthGroupAccess::where('uid', $this->auth->id)->find();




            if ($AuthGroupAccessData->group_id==3) {//代理为商户添加余额
                $data=$this->model->get(['id' => $this->auth->id]);
                if ($data->money<$params['money']) {
                     $this->error('代理余额不足，无法为商户添加余额');
                }

            }


            if ($ids==$this->auth->id) {
                    $this->error('无法给自己充值');
            }





            if ($params) {


                $result = $this->model->where('id', $ids)->setInc('money', $params['money']);//商户增加余额

                if ($result === false) {
                    $this->error($this->model->getError());
                }

                //余额明细
                AdminMoneyLog::create([
                    'admin_id'     => $ids,
                    'type'   => 1,
                    'money'       => $params['money'],
                    'note'  => '后台充值',
                    'create_at'  => date('Y-m-d h:i:s', time()),
                ]);




            //代理扣除对应余额

            if ($AuthGroupAccessData->group_id==3) {

                $this->model->where('id', $this->auth->id)->setDec('money', $params['money']);
                AdminMoneyLog::create([
                    'admin_id'     => $this->auth->id,
                    'type'   => 2,
                    'money'       => $params['money'],
                    'note'  => '代理为下级充值扣除余额',
                    'create_at'  => date('Y-m-d h:i:s', time()),
                ]);

            }





                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();





    }

    //【添加】或【编辑】提交时的数据检查
    private function check()
    {
        $row = $this->request->post("row/a");
        $shopId = intval($row['shop_id']);
        $param = $this->request->post();

        //当分组为管理员或商户时，商户ID不能为空
        if (in_array($param['group'][0], array('1', '2')) && $shopId < 1) {
            $this->error('商户不能为空');
        }

        //当分组为代理时，代理区域不能为空
        if ($param['group'][0] === '3' && empty($param['row']['agent_city'])) {
            $this->error('代理区域不能为空');
        }
    }

    //充值视频额度
    public function add_video_quota($ids = null)
    {
        if ($this->request->isPost()) {
            $quota = intval($this->request->post('video_quota'));
            $targetId = intval($ids);

            //获取自身的所有下级账号
            $dbPrefix = config('database.prefix');
            $adminData = Db::table($dbPrefix . 'admin')->field('id,pid')->select();
            $posterityIdData = getPosterityId($adminData, $this->auth->id);
            $posterityIdData = array_flip($posterityIdData);

            //检查是否是自身的下级账号
            if (!isset($posterityIdData[$targetId])) {
                $this->error('该账号不是您的下级账号');
            }

            //检查自身是否有足够的额度充值给目标账号。如果是初始管理员，则初始管理员额度无限，不用检查初始管理员的是否有足够额度给下级充值
            if ($this->auth->id !== 1) {
                $userInfo = Db::table($dbPrefix . 'admin')->find($this->auth->id);
                if ($userInfo['last_aivideo_nums'] < $quota) {
                    $this->error('您没有足够的额度充值给所选账号');
                }
            }

            Db::startTrans();
            //目标账号增加视频额度
            $result1 = $this->model->where('id', $targetId)->setInc('last_aivideo_nums', $quota);
            //自身减少视频额度。如果是初始管理员，则初始管理员额度无限，不用扣除初始管理员的额度。
            $result2 = true;
            if ($this->auth->id !== 1) {
                $result2 = $this->model->where('id', $this->auth->id)->setDec('last_aivideo_nums', $quota);
            }
            //视频额度充值流水
            $result3 = Db::table($dbPrefix . 'admin_video_log')->insert([
                'source_user_id' => $this->auth->id,
                'target_user_id' => $targetId,
                'quota' => $quota,
            ]);

            if ($result1 && $result2 && $result3) {
                Db::commit();
                $this->success('充值视频额度成功');
            } else {
                Db::rollback();
                $this->error('保存数据时发生错误');
            }
        }

        return $this->view->fetch();
    }

}
